<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\model\MerchantDistributionConfig;
use app\model\DistributionRecord;

class DistributionController
{
    /**
     * 获取分销配置
     */
    public function getConfig()
    {
        $merchantId = request()->merchant_id;
        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => MerchantDistributionConfig::getConfig($merchantId)
        ]);
    }

    /**
     * 更新分销配置
     */
    public function updateConfig()
    {
        $merchantId = request()->merchant_id;
        $enabled = input('distribution_enabled/b');
        $level1Rate = input('level1_rate/f');
        $level2Rate = input('level2_rate/f');

        // 验证分销比例
        if ($level1Rate < 0 || $level1Rate > 1 || $level2Rate < 0 || $level2Rate > 1) {
            return json(['code' => 1, 'msg' => '分销比例必须在0-1之间']);
        }

        if ($level1Rate + $level2Rate > 1) {
            return json(['code' => 1, 'msg' => '分销比例总和不能超过100%']);
        }

        // 更新或创建配置
        MerchantDistributionConfig::updateOrCreate(
            ['merchant_id' => $merchantId],
            [
                'distribution_enabled' => $enabled,
                'level1_rate' => $level1Rate,
                'level2_rate' => $level2Rate
            ]
        );

        // 清除缓存
        MerchantDistributionConfig::clearCache($merchantId);

        return json(['code' => 0, 'msg' => '更新成功']);
    }

    /**
     * 获取分销统计数据
     */
    public function statistics()
    {
        $merchantId = request()->merchant_id;
        $userId = input('user_id/d', 0);
        
        if (!$userId) {
            return json(['code' => 1, 'msg' => '用户ID不能为空']);
        }

        $stats = DistributionRecord::getUserStats($userId, $merchantId);
        
        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $stats
        ]);
    }

    /**
     * 获取分销记录列表
     */
    public function records()
    {
        $merchantId = request()->merchant_id;
        $userId = input('user_id/d', 0);
        $status = input('status/d', -1);
        $page = input('page/d', 1);
        $limit = input('limit/d', 20);

        $where = ['merchant_id' => $merchantId];
        if ($userId) {
            $where['user_id'] = $userId;
        }
        if ($status >= 0) {
            $where['status'] = $status;
        }

        $list = DistributionRecord::where($where)
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ]);

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $list
        ]);
    }
} 